/**
 * Created by Kiva on 17/1/3.
 */
(function() {
    $(document).ready(function() {

        $(".page-nav").find("li").click(function() {
            var $li = $(this);
            menuClick($li);
        });
        $(".page-container-tabs-content:first").on("click","a", function(e) {
            tabClick(this,true);
        });
        $(".left-button").click(function() {
            tabLeftClick(this);
        });
        $(".right-button").click(function() {
            tabRightClick(this);
        });
    });

    // $(window).resize(function() {
    //     tabMove($(".page-container-tabs:first"), tabMoveLeft());
    // });


    function addiFrame(href, $div, count) {
        var id = href.replace("#", "");
        var html = '<div role="tabpanel" class="tab-pane fade" id="' + id + count + '" data-number="' + count + '"></div>';
        $div.append(html);
        var $tabPanel = $("#" + id + count);
        $.ajax({
            async: false,
            url: id + ".html",
            dataType: "html",
            success: function(data, textStatus) {
                $tabPanel.empty().append(data);
            }
        });


        /* $tabPanel.load(id+".html",function(){
         		log4j.info("load success");
         });*/
    }

    function getActiveA() {
        return $(".page-container-tabs-content").find("a.active");
    }

    function tabRightClick(button) {
        var $pageTabs = $(button).siblings("nav:first");
        var $pageTabsContent = $pageTabs.find(".page-container-tabs-content:first");
        var leftOffset = $(".navbar-static-side:first").outerWidth(true) + $(".left-button:first").outerWidth(true);
        var rightOffset = $(button).offset().left;
        var marginLeft = parseFloat($pageTabs.css("margin-left"));
        var $a = getFirstVisibleA($pageTabsContent, leftOffset);
        var $lastA = $pageTabsContent.find("a:last");
        var $next = $a;
        if ($lastA.offset().left + getWidth($lastA) >= rightOffset) {
            for (var i = 0; i < 2; i++) {
                marginLeft -= $next.outerWidth(true);
                $next = $next.next();
            }
        }
        $pageTabs.animate({
            "marginLeft": marginLeft
        }, 300);
    }

    function tabLeftClick(button) {
        var $pageTabs = $(button).siblings("nav:first");
        var $pageTabsContent = $pageTabs.find(".page-container-tabs-content:first");
        var leftOffset = $(button).offset().left + $(button).outerWidth(true);
        var marginLeft = parseFloat($pageTabs.css("margin-left"));
        var $a = getFirstVisibleA($pageTabsContent, leftOffset);
        var $pre = $a.prev();
        for (var i = 0; i < 2; i++) {
            if ($pre.length > 0) {
                marginLeft += getWidth($pre);
                $pre = $pre.prev();
            }
        }
        $pageTabs.animate({
            "marginLeft": marginLeft
        }, 300, "linear", function() {
            if (parseFloat($pageTabs.css("margin-left")) > $(button).outerWidth(true)) {
                $pageTabs.animate({
                    "marginLeft": $(button).outerWidth(true)
                }, 100, "linear");
            }
        });
    }

    function getFirstVisibleA($pageTabsContent, leftOffset) {
        var $a = $pageTabsContent.find("a:first");
        $pageTabsContent.find("a").each(function() {
            $a = $(this);
            if ($a.offset().left >= leftOffset) {
                return false;
            }
        });
        //log4j.info($a.text());
        return $a;
    }

    function menuClick($li) {
        var $a = $li.children("a:first");
        var count = $a.attr("data-count");
        var connect = $a.attr("data-connect");
        if ($a.hasClass("menuItem")) {
            var src = $a.attr("href");
            // var flag=true;
            // $(".page-container-tabs-content:first").children("a").each(function () {
            //     var $this=$(this);
            //     for(var i=connect;i<count;i++){
            //         if($this.attr("data-id")==src+i){
            //             //log4j.info(src+i);
            //             tabClick(this);
            //             flag=false;
            //             $a.attr("data-connect",i);
            //             return false;
            //         }
            //     }
            // });
            // if(flag){
            addTab(src, $a.text() + count, count);
            $a.attr("data-connect", parseInt(count));
            $a.attr("data-count", parseInt(count) + 1);
            tabClick($(".page-container-tabs-content:first").children("a:last"));
            // }
        }
    }


    function tabClick(tab) {
        var $tab = $(tab);
        $(".page-container-tabs-content:first").children("a").removeClass("active activity");
        $tab.addClass("active activity");
        tabMove($(".page-container-tabs:first"), tabMoveLeft());
        $(".page-container-content").children().removeClass("in active").addClass("d-n");
        $($tab.attr("data-id")).removeClass("d-n").addClass("in active");
        if (getContentId().indexOf('record') == -1 && getContentId().indexOf('history') == -1) {
            // getJqueryContent(getContentId()).find("#clinic_info").text('主诉：' + getJqueryContent('record').find("#visSymptom").val() + "，诊断：" + recordinfo);
            var visSymptom = getJqueryContent('record').find("#visSymptom").val() || Param.getParam("visSymptom", "record")
            var visPresentHis = getJqueryContent('record').find("#visPresentHis").val() || Param.getParam("visPresentHis", "record")
            Page.getJquery("#clinic_info .visSymptom").val(visSymptom)
            Page.getJquery("#clinic_info .visPresentHis").val(visPresentHis)
        }
        if (getContentId().indexOf('clinic_ch_medicine_2') != -1) synchronizedData()
        if (getContentId().indexOf('clinic_west_medicine_2') != -1) synchronizedData2()
        if (getContentId().indexOf('record') != -1) synchronizedData1()

    }




    function addTab(dataId, text, count) {
        var $pageTabsContent = $(".page-container-tabs-content:first");
        $pageTabsContent.children("a").removeClass("activity");
        var html = '<a href="javascript:void(0);" class="menuTab activity" data-id="' + dataId + count + '">' + text + '<span><i class="iconfont icon-guanbi"></i></span></a>';
        $pageTabsContent.append(html);
        $pageTabsContent.find("a:last").on("click", function() {
            tabClick(this);
        });
        $pageTabsContent.find("a:last").find("span").on("click", function() {
            if (localStorage.getItem("workStyle") == "clinicDoctor") {
                if (confirm("确定要删除？")) {
                    countSubtract(dataId, this)
                    tabClose(this);
                    return false;
                }
            } else {
                countSubtract(dataId, this)
                tabClose(this);
                return false;
            }
        });
        addiFrame(dataId, $(".page-container-content"), count);
    }

    // 关闭tab后, count--
    function countSubtract(dataId, el) {
        let tabIndex = $(el).parents('a:first').text().slice(-1)
        let prescribingType = dataId.split('_')[1]
        $('#buttonNav .menuItem').each((index, item) => {
            if ($(item).attr('href').indexOf(prescribingType) !== -1) {
                if ($(item).attr('data-count') - tabIndex === 1) {
                    let count = parseInt($(item).attr('data-count')) - 1
                    $(item).attr('data-count', count)
                }
            }
        })
    }

    function tabClose(i) {
        var $close = $(i);
        var $tab = $close.parent();
        var $next = $tab.next();
        var $pre = $tab.prev();
        if (!$tab.hasClass("active")) {
            $tab.remove();
        } else {
            $next.length > 0 ? ($tab.remove(), tabClick($next)) : ($tab.remove(), tabClick($pre));
        }
        tabMoveLeft();
        $($tab.attr("data-id")).remove();
    }

    function tabMoveLeft() {
        var $pageTabsContent = $(".page-container-tabs-content:first");
        var $lastTab = $pageTabsContent.find("a:last");
        var leftOffset = $(".left-button:first").outerWidth(true) + $(".left-button:first").offset().left;
        var $firstVisibleA = getFirstVisibleA($pageTabsContent, leftOffset);
        var $pageTabs = $(".page-container-tabs:first");
        var marginLeft = parseFloat($pageTabs.css("margin-left"));
        if ($lastTab.offset().left + getWidth($lastTab) + getWidth($firstVisibleA) < $(".right-button:first").offset().left) {
            marginLeft += getWidth($firstVisibleA);
            if (marginLeft > 20) marginLeft = 20;
        }
        $pageTabs.stop().animate({
            "marginLeft": marginLeft
        }, 200);
    }

    function getWidth($node) {
        var width = 0;
        $($node).each(function() {
            width += $(this).outerWidth(true);
        });
        return width;
    }

    function tabMove($pageTabs, fn) {
        fn = fn || function() {};
        var $active = $pageTabs.find(".active");
        var activeLeft = $active.offset().left;
        var activeW = getWidth($active);
        var initMarginLeft = getWidth($pageTabs.prev());
        var leftConfine = $pageTabs.prev().offset().left + initMarginLeft;
        var rightConfine = $pageTabs.next().offset().left;
        var middleW = rightConfine - leftConfine;
        var $content = $pageTabs.find(".page-container-tabs-content:first");
        var contentW = getWidth($content);
        var marginLeft = initMarginLeft;
        var $activeNext = $active.next();
        var nextLeft;
        var nextW;
        var $lastTab = $pageTabs.find("a:last");
        var $firstVisibleA = getFirstVisibleA($content, leftConfine);
        if ($activeNext.length > 0) {
            nextLeft = $activeNext.offset().left;
            nextW = getWidth($activeNext);
        }
        //260 877
        // log4j.info("第一个条件："+!!($activeNext.length>0));
        // log4j.info("第二个条件："+nextLeft+"/"+nextW+"/"+!!(nextLeft-rightConfine<0 && nextLeft-rightConfine+nextW>=0));
        // log4j.info("第三个条件："+!!(nextLeft-rightConfine>=0));
        var flag = false;
        //总长度小于tab滚动中间可见区域的长度
        if (contentW <= middleW) {
            marginLeft = initMarginLeft;
            //log4j.info("总长度小于tab滚动中间可见区域的长度");
        } else if ($active.prev().length > 0 && parseInt($active.prev().offset().left) < leftConfine) {
            marginLeft = -getWidth($active.prev().prevAll()) + initMarginLeft;
            //log4j.info("上一个标签");
        } else if ((activeLeft - rightConfine < 0 && activeLeft - rightConfine + activeW >= 0) || activeLeft - rightConfine >= 0 || ($activeNext.length > 0 && ((nextLeft - rightConfine < 0 && nextLeft - rightConfine + nextW >= 0) || nextLeft - rightConfine >= 0))) { //标签在可见区域后面
            var $pre = $active.prev();
            while (parseInt($pre.offset().left) > leftConfine) {
                $pre = $pre.prev();
                if ($pre.prev().length == 0) break;
            }
            marginLeft = parseFloat($pageTabs.css("margin-left")) - getWidth($pre);
            flag = true;
            //log4j.info("标签在可见区域后面");
        } else if ($lastTab.offset().left + $lastTab.outerWidth(true) + $firstVisibleA.outerWidth(true) < rightConfine && parseFloat($pageTabs.css("marginLeft")) < initMarginLeft) {
            marginLeft = parseFloat($pageTabs.css("margin-left")) + $firstVisibleA.outerWidth(true);
        } else {
            marginLeft = parseFloat($pageTabs.css("margin-left"));
            //log4j.info("不变");
        }
        var time = 300;
        if (flag) {
            time = 150;
        }
        $pageTabs.stop().animate({
            "marginLeft": marginLeft
        }, time, "linear", function() {
            if (flag) {
                tabMove($pageTabs);
            }
            fn();
        });
    }

    function scrollBar($nav) {
        var $navP = $nav.parent();
        var $scrollBar = $nav.siblings(".scrollBar:first");
        var timer = setTimeout(function() {
            $scrollBar.fadeOut("slow");
        }, 1500);
        $nav.on("mousewheel", function(event, delta, deltaX, deltaY) {
            clearTimeout(timer);
            var navHeight = $nav.height();
            var navPHeight = $navP.height();
            $scrollBar.height(navPHeight / 2);
            var ratio = Math.abs($scrollBar.height() / (navHeight - navPHeight));
            var speed = -deltaY;
            //log4j.info(speed);
            var scrollBarMarginTop = parseFloat($scrollBar.css("margin-top"));
            var navMarginTop = parseFloat($nav.css("margin-top"));
            if (navHeight > navPHeight) {
                $scrollBar.css("display", "block");
                if (parseFloat($scrollBar.css("margin-top")) < 0) {
                    // log4j.info("3:"+parseFloat($scrollBar.css("margin-top")));
                    lessThanZero()
                } else if (parseFloat($scrollBar.css("margin-top")) <= $scrollBar.height()) {
                    // log4j.info("1:"+$scrollBar.css("margin-top"));
                    $scrollBar.stop().animate({
                        "marginTop": scrollBarMarginTop + speed * ratio
                    }, 300, "linear", function() {
                        lessThanZero();
                        moreThanHeight();
                    });
                    $nav.stop().animate({
                        "marginTop": navMarginTop - speed
                    }, 300, "linear");
                } else if (parseFloat($scrollBar.css("margin-top")) > $scrollBar.height()) {
                    // log4j.info("2:"+parseFloat($scrollBar.css("margin-top")));
                    moreThanHeight()
                }
            }

            function lessThanZero() {
                if (parseFloat($scrollBar.css("margin-top")) < 0) {
                    $scrollBar.stop().animate({
                        "marginTop": 0
                    }, 200);
                    $nav.stop().animate({
                        "marginTop": 0
                    }, 200);
                }
            }

            function moreThanHeight() {
                if (parseFloat($scrollBar.css("margin-top")) > $scrollBar.height()) {
                    $scrollBar.stop().animate({
                        "marginTop": $scrollBar.height()
                    }, 200);
                    $nav.stop().animate({
                        "marginTop": navPHeight - navHeight
                    }, 200);
                }
            }
            timer = setTimeout(function() {
                $scrollBar.fadeOut("slow");
            }, 1500);
        });
    }

})();

function getJqueryContent(contentId) {
    if (contentId) {
        return $("#" + contentId);
    }
    return $("#" + getContentId());
}

function getContentId() {
    var contentId = $(".page-container-tabs-content").children(".activity:first").length >= 1 ? $(".page-container-tabs-content").children(".activity:first").data("id") : "";
    return contentId.replace("#", "");
}

function reload(src) {
    var $navTabsContent = $(".page-container-tabs-content");
    var $a = $navTabsContent.find(".activity:first");
    var $tabPanel = $($a.attr("data-id"));
    $tabPanel.html("");
    $tabPanel.load(src);
}